package com.fyyg.common.redis;


import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisBase {
	static Logger log = Logger.getLogger(RedisBase.class);
	
	private static RedisBase base = null;
	private static List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
	private static ShardedJedisPool pool = null;
	private RedisBase() throws Exception{
		if(null == pool)
			initPool();
	}
	
	public synchronized static RedisBase getInstance(){
		if(null ==base)
			try {
				base = new RedisBase();
			} catch (Exception e) {
				e.printStackTrace();
				log.error("error getInstance:"+e.getMessage());
			}
		return base;
	}
	
	/**
	 * 初始化redis pool
	 */
	private synchronized static void initPool() throws Exception{
		pool = null;
		shards = new ArrayList<JedisShardInfo>();
		for (int i = 0; i < RedisConfig.hosts.length; i++) {
			int port = Integer.valueOf(RedisConfig.ports[i]);
			if ( (RedisConfig.hosts[i].trim().length()>7) && (port>1024) ){
				shards.add(new JedisShardInfo(RedisConfig.hosts[i],RedisConfig.ports[i]));
				System.out.println("RedisServer starting NO["+i+"]host["+RedisConfig.hosts[i]+"]port["+RedisConfig.ports[i]+"]");
			}
		}
		JedisPoolConfig config = new JedisPoolConfig();

		//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
		config.setBlockWhenExhausted(false);
		
		//最大空闲连接数,20个
		config.setMaxIdle(RedisConfig.maxidle);
		
		//最大连接数, 1024
		config.setMaxTotal(RedisConfig.maxactive);
		
		//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
		config.setMaxWaitMillis(RedisConfig.maxwait);

		//多长时间检查一次连接池中空闲的连接
		config.setTimeBetweenEvictionRunsMillis(10000);

		//空闲连接多长时间后会被收回
		config.setMinEvictableIdleTimeMillis(10000);
		
		// 获得一个jedis实例的时候是否检查连接可用性（ping()）
		config.setTestOnBorrow(RedisConfig.testOnBorrow);
		
	    pool = new ShardedJedisPool(config, shards);
	}
	
	public ShardedJedisPool getPool() throws Exception {
		if (null == pool)
			initPool();
	    return pool;
	}
	
	public void resetPool() throws Exception {
		pool.destroy();
		initPool();
	}
	
	public ShardedJedis getResource() {
		ShardedJedis jedis = null;
		try {
			jedis = getPool().getResource();
		}catch(Exception e) {
			log.error("[获取redis连接池异常]，原因："+e.getMessage());
		}
		return jedis;
	}
	
	/**
	 * 释放资源
	 */  
	public void returnBrokenResource(ShardedJedis shardedJedis) {
		try {
			pool.returnBrokenResource(shardedJedis);
		} catch (Exception e) {
		}
		
	}

	/**
	 * 关闭连接
	 */ 
	public void returnResource(ShardedJedis shardedJedis){
		
		try {
			pool.returnResource(shardedJedis);
		} catch (Exception e) {
		}
	}
	
	public synchronized void closePool() throws Exception{
		pool.destroy();
		pool = null;
	}
	
	
	
	
}
